package com.kai.service.config;

import com.alibaba.fastjson.JSON;
import com.kai.admin.api.TokenApi;
import com.kai.auth.config.SecurityProperties;
import com.kai.auth.data.LoginUser;
import com.kai.auth.util.LoginUserUtil;
import com.kai.common.util.WebUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

/**
 * <p>
 * feign配置类
 * </p>
 *
 * @author weijk
 * @since 2023/7/17
 */
@Configuration
@EnableFeignClients(clients = {TokenApi.class})
public class FeignConfig implements RequestInterceptor {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        if (Objects.isNull(loginUser)) {
            requestTemplate.header(securityProperties.getTokenHeader(), WebUtil.getHeader(securityProperties.getTokenHeader()));
        } else {
            requestTemplate.header(LoginUserUtil.LOGIN_USER_HEADER, JSON.toJSONString(loginUser));
        }
    }
}
